<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>好稿列表</span>
          <el-button size="mini" style="float: right" @click="router.go(-1)">返回</el-button>
        </div>
      </template>

      <span style="font-size: 15px"> 年份：</span>
      <el-select v-model="searchForm.year" placeholder="Select" style="width: 140px" @change="searchOrder">
        <el-option v-for="item in years" :key="item.year" :value="item.year" />
      </el-select>

      <span style="font-size: 15px; margin-left: 20px"> 月份：</span>
      <el-select v-model="searchForm.month" placeholder="Select" style="width: 80px" @change="searchOrder">
        <el-option v-for="item in 12" :key="item" :value="item" :label="`${item}月`" />
      </el-select>

      <el-button type="success" style="float:right;margin-right:10px" @click="download">
        导出当月好稿数据<el-icon class="el-icon--right">
          <Download />
        </el-icon>
      </el-button>
      <h3>编辑</h3>
      <el-table :data="tableDataBianji" border style="width: 100%; margin-top: 20px" :row-click-expand="true">
        <el-table-column type="expand">
          <template #default="scope">
            <div v-if="Array.isArray(scope.row.files)" style="margin-left: 50px;">
              <div v-if="scope.row.files[0].id != null">
                <div class="files-wrapper">
                  <template v-for="(item, index) in scope.row.files">
                    <div class="file-container" @mouseover="hover = `${scope.$index}-${index}`"
                      @mouseleave="hover = null">
                      <el-image v-if="tool.isImage(item.url)" :src="`${baseURL}/${item.url}`" :zoom-rate="1.2"
                        :max-scale="7" :min-scale="0.2" :initial-index="index" :preview-teleported="true"
                        :preview-src-list="scope.row.files.filter(file => tool.isImage(file.url)).map(file => `${baseURL}/${file.url}`)
                          " fit="cover" class="image" @load="onLoadImage" />
                      <video v-else-if="tool.isVideo(item.url)" :src="`${baseURL}/${item.url}`" controls class="video"
                        preload="metadata"></video>
                      <a :href="`${baseURL}/${item.url}`" class="file-download" target="_blank" v-else>
                        <div class="doc">
                          <span>{{ item.original_name }}</span>
                        </div>
                      </a>
                      <el-button type="danger" :icon="Delete" circle @click="delFile(scope.row.id, item.id)"
                        v-show="hover === `${scope.$index}-${index}`"
                        style="position: absolute;right:20px;top:10px;width:30px;height:30px" />
                    </div>
                  </template>
                </div>
              </div>
              <div v-else style="margin: 10px 10px; color: gray">
                该项目没上传文件
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="序号" width=80 align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="项目名称" />
        <el-table-column prop="member" label="人员" width="120" align="center">
          <template #default="scope">
            <el-tag class="ml-2">{{ scope.row.member }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="myRemark" label="备注">
          <template #default="scope">
            <span v-html="formatRemark(scope.row.myRemark)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="goodRemark" label="评选理由">
          <template #default="scope">
            <div v-for="(vote, index) in scope.row.votes" :key="index"><span v-html="formatVote(vote)"></span></div>
          </template>
        </el-table-column>
        <el-table-column prop="goodScore" label="好稿得分">
          <template #default="scope">
            <div> {{ (scope.row.votes.reduce((sum, vote) => sum + parseInt(vote.goodScore, 10), 0) /
              scope.row.votes.length).toFixed(0) }}</div>
          </template>
        </el-table-column>
      </el-table>
      <h3>设计</h3>
      <el-table :data="tableDataSheji" border style="width: 100%; margin-top: 20px" :row-click-expand="true">
        <el-table-column type="expand">
          <template #default="scope">
            <div v-if="Array.isArray(scope.row.files)" style="margin-left: 50px;">
              <div v-if="scope.row.files[0].id != null">
                <div class="files-wrapper">
                  <template v-for="(item, index) in scope.row.files">
                    <div class="file-container" @mouseover="hover = `${scope.$index}-${index}`"
                      @mouseleave="hover = null">
                      <el-image v-if="tool.isImage(item.url)" :src="`${baseURL}/${item.url}`" :zoom-rate="1.2"
                        :max-scale="7" :min-scale="0.2" :initial-index="index" :preview-teleported="true"
                        :preview-src-list="scope.row.files.filter(file => tool.isImage(file.url)).map(file => `${baseURL}/${file.url}`)
                          " fit="cover" class="image" @load="onLoadImage" />
                      <video v-else-if="tool.isVideo(item.url)" :src="`${baseURL}/${item.url}`" controls class="video"
                        preload="metadata"></video>
                      <a :href="`${baseURL}/${item.url}`" class="file-download" target="_blank" v-else>
                        <div class="doc">
                          <span>{{ item.original_name }}</span>
                        </div>
                      </a>
                      <el-button type="danger" :icon="Delete" circle @click="delFile(scope.row.id, item.id)"
                        v-show="hover === `${scope.$index}-${index}`"
                        style="position: absolute;right:20px;top:10px;width:30px;height:30px" />
                    </div>
                  </template>
                </div>
              </div>
              <div v-else style="margin: 10px 10px; color: gray">
                该项目没上传文件
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="序号" width=80 align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="项目名称" />
        <el-table-column prop="member" label="人员" width="120" align="center">
          <template #default="scope">
            <el-tag class="ml-2">{{ scope.row.member }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="myRemark" label="备注">
          <template #default="scope">
            <span v-html="formatRemark(scope.row.myRemark)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="goodRemark" label="评选理由">
          <template #default="scope">
            <div v-for="(vote, index) in scope.row.votes" :key="index"><span v-html="formatVote(vote)"></span></div>
          </template>
        </el-table-column>
        <el-table-column prop="goodScore" label="好稿得分">
          <template #default="scope">
            <div> {{ (scope.row.votes.reduce((sum, vote) => sum + parseInt(vote.goodScore, 10), 0) /
              scope.row.votes.length).toFixed(0)}}</div>
          </template>
        </el-table-column>
      </el-table>
      <h3>技术</h3>
      <el-table :data="tableDataJishu" border style="width: 100%; margin-top: 20px" :row-click-expand="true">
        <el-table-column type="expand">
          <template #default="scope">
            <div v-if="Array.isArray(scope.row.files)" style="margin-left: 50px;">
              <div v-if="scope.row.files[0].id != null">
                <div class="files-wrapper">
                  <template v-for="(item, index) in scope.row.files">
                    <div class="file-container" @mouseover="hover = `${scope.$index}-${index}`"
                      @mouseleave="hover = null">
                      <el-image v-if="tool.isImage(item.url)" :src="`${baseURL}/${item.url}`" :zoom-rate="1.2"
                        :max-scale="7" :min-scale="0.2" :initial-index="index" :preview-teleported="true"
                        :preview-src-list="scope.row.files.filter(file => tool.isImage(file.url)).map(file => `${baseURL}/${file.url}`)
                          " fit="cover" class="image" @load="onLoadImage" />
                      <video v-else-if="tool.isVideo(item.url)" :src="`${baseURL}/${item.url}`" controls class="video"
                        preload="metadata"></video>
                      <a :href="`${baseURL}/${item.url}`" class="file-download" target="_blank" v-else>
                        <div class="doc">
                          <span>{{ item.original_name }}</span>
                        </div>
                      </a>
                      <el-button type="danger" :icon="Delete" circle @click="delFile(scope.row.id, item.id)"
                        v-show="hover === `${scope.$index}-${index}`"
                        style="position: absolute;right:20px;top:10px;width:30px;height:30px" />
                    </div>
                  </template>
                </div>
              </div>
              <div v-else style="margin: 10px 10px; color: gray">
                该项目没上传文件
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="序号" width=80 align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="项目名称" />
        <el-table-column prop="member" label="人员" width="120" align="center">
          <template #default="scope">
            <el-tag class="ml-2">{{ scope.row.member }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="myRemark" label="备注">
          <template #default="scope">
            <span v-html="formatRemark(scope.row.myRemark)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="goodRemark" label="评选理由">
          <template #default="scope">
            <div v-for="(vote, index) in scope.row.votes" :key="index"><span v-html="formatVote(vote)"></span></div>
          </template>
        </el-table-column>
        <el-table-column prop="goodScore" label="好稿得分">
          <template #default="scope">
            <div> {{ (scope.row.votes.reduce((sum, vote) => sum + parseInt(vote.goodScore, 10), 0) /
              scope.row.votes.length).toFixed(0) }}</div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import workApi from '../../api/work'
import * as XLSX from 'xlsx'
import { useRoute, useRouter } from 'vue-router'
import tool from '../../tools/tool'

const route = useRoute()
const router = useRouter()
const tableData = ref([])
const tableDataBianji = ref([])
const tableDataSheji = ref([])
const tableDataJishu = ref([])
const years = ref()
// 搜索条件
const searchForm = reactive({ ...route.query });
// 获取全局变量
const baseURL = window.globalConfig.baseURL
const username = sessionStorage.getItem('username')

onMounted(async () => {
  const yearRes = await workApi.getDistinctYears()
  years.value = yearRes.data
  console.log(years.value)
  searchForm.year = route.query.year
  searchForm.month = route.query.month
  searchOrder()
  searchForm.month = route.query.month + "月"
})

// 获取数据列表
const searchOrder = async () => {
  tableData.value = []
  tableDataBianji.value = []
  tableDataSheji.value = []
  tableDataJishu.value = []
  const resData = await workApi.getGoodListByMonth(searchForm)

  const idMap = new Map();

  resData.data.forEach((item) => {
    const id = item.order_id;

    if (!idMap.has(id)) {
      idMap.set(id, {
        order_id: id,
        product_name: item.product_name,
        member: item.member,
        myRemark: item.myRemark,
        type: item.type,
        votes: [],
        files: []
      });
    }

    const orderData = idMap.get(id);

    // 添加投票信息到 votes 数组，避免重复
    if (!orderData.votes.some(vote => vote.voter === item.voter && vote.goodRemark === item.remark)) {
      orderData.votes.push({
        voter: item.voter,
        goodRemark: item.remark,
        goodScore: item.score,
        create_time: item.create_time,
      });
    }

    // 检查并添加文件信息到 files 数组，避免重复
    if (!orderData.files.some(file => file.id === item.file_id)) {
      orderData.files.push({
        id: item.file_id,
        url: item.url,
        original_name: item.original_name
      });
    }
  });

  // 转换 Map 为数组
  const result = Array.from(idMap.values());
  tableData.value = result;

  // 遍历 tableData 中的每个记录
  tableData.value.forEach((item) => {
    if (item.type == "编辑") {
      tableDataBianji.value.push(item);
    }
    if (item.type == "设计") {
      tableDataSheji.value.push(item);
    }
    if (item.type == "技术") {
      tableDataJishu.value.push(item);
    }
  });
}

const formatVote = (vote) => {
  return `<strong>${vote.voter}</strong>： ${vote.goodRemark}`;
}


const formatRemark = (remark) => {
  if (!remark) return '';

  // 正则表达式匹配 URL
  const urlPattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;

  // 将 URL 替换为超链接并替换换行符为 <br>
  return remark
    .replace(urlPattern, (url) => `<a href="${url}" target="_blank">${url}</a>`)
    .replace(/\n/g, '<br>');
};

// 导出数据 begin
const download = () => {
  const wsData = [];

  // 大标题
  const mainTitle = `${searchForm.year}年${searchForm.month}月好稿项目`;
  wsData.push([mainTitle]);
  wsData.push([]); // 空行

  // 编辑
  wsData.push(['编辑']);
  wsData.push(['序号', '项目名称', '人员名称', '评选理由', '好稿得分']);
  tableDataBianji.value.forEach((item, index) => {
    wsData.push([
      index + 1,
      item.product_name,
      item.member,
      item.votes.map(vote => `${vote.voter}: ${vote.goodRemark}`).join(', '),
      (item.votes.reduce((sum, vote) => sum + parseInt(vote.goodScore, 10), 0) / item.votes.length).toFixed(0)  // 计算平均分并添加
    ]);
  });
  wsData.push([]); // 空行

  // 设计
  wsData.push(['设计']);
  wsData.push(['序号', '项目名称', '人员名称', '评选理由','好稿得分']);
  tableDataSheji.value.forEach((item, index) => {
    wsData.push([
      index + 1,
      item.product_name,
      item.member,
      item.votes.map(vote => `${vote.voter}: ${vote.goodRemark}`).join(', '),
      (item.votes.reduce((sum, vote) => sum + parseInt(vote.goodScore, 10), 0) / item.votes.length).toFixed(0)  // 计算平均分并添加
    ]);
  });
  wsData.push([]); // 空行

  // 技术
  wsData.push(['技术']);
  wsData.push(['序号', '项目名称', '人员名称', '评选理由','好稿得分']);
  tableDataJishu.value.forEach((item, index) => {
    wsData.push([
      index + 1,
      item.product_name,
      item.member,
      item.votes.map(vote => `${vote.voter}: ${vote.goodRemark}`).join(', '),
      (item.votes.reduce((sum, vote) => sum + parseInt(vote.goodScore, 10), 0) / item.votes.length).toFixed(0)  // 计算平均分并添加
    ]);
  });

  const ws = XLSX.utils.aoa_to_sheet(wsData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '好稿项目');

  // 设置大标题居中
  const merge = [
    { s: { r: 0, c: 0 }, e: { r: 0, c: 3 } } // 合并第一行的单元格
  ];
  ws['!merges'] = merge;
  ws['A1'].s = {
    font: { sz: 16, bold: true }, // 设置字体大小和加粗
    alignment: { horizontal: 'center', vertical: 'center' } // 设置居中对齐
  };

  XLSX.writeFile(wb, `${searchForm.year}年${searchForm.month}月好稿项目表.xlsx`);
}
// 导出数据 end


</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 100%;
  height: 100%;
}

.el-tag {
  margin: 5px 5px 5px 0;
}

.el-tab {
  margin: 20px 10px;
}

:deep(.warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

:deep(.success-row) {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

h3 {
  margin-left: 10px;
  margin-bottom: -10px;
  margin-top: 40px;
  color: #1aa1a1;
  text-decoration: underline;
}

.files-wrapper {
  display: flex;
  flex-wrap: wrap;
  /* 允许换行 */
  align-items: flex-start;
  /* 确保所有项在交叉轴（垂直方向）上对齐 */
}

.file-container {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
  /* 防止图片超出容器 */
  border: 1px solid #dcdcdc;
  /* 可以根据需要添加边框 */
  border-radius: 8px;
  /* 圆角效果 */
  background-color: #f9f9f9;
  /* 背景颜色 */
  margin: 8px;
}

.file-container .image,
.file-container .video {
  transition: transform 0.3s linear;
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

.file-container:hover .image,
.file-container:hover .doc,
.file-container:hover .video {
  transform: scale(1.05);
}

.file-container .video {
  width: 100%;
  /* 确保视频宽度填满容器 */
  height: auto;
  /* 让高度自适应 */
}



.doc {
  width: 150px;
  height: 150px;
  border: 1px solid #9bb0e0;
  margin: 0 10px;
  padding: 10px;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #f6f8fc, #e9eef9);
  transition: transform 0.3s linear;
}

.doc span {
  display: inline-block;
  vertical-align: middle;
  padding: 0 10px;
  width: 60%;
  overflow: hidden;
  white-space: normal;
  word-wrap: break-word;
  line-height: normal;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
  color: #6a6a6b;
  font-weight: bold;
}
</style>
